﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Communergy.Common;
using Communergy.Repository.SQLite;

namespace Communergy.Repository
{
    public class SQLiteRealtimeRepository : IRealtimeRepository
    {


        #region IRealtimeRepository Members
        CommunergySQLiteEntities sqlite;

        public SQLiteRealtimeRepository(IUnitOfWork unitOfWork)
        {
            //will return null if not communergyEntities
            sqlite = unitOfWork as CommunergySQLiteEntities;
            if (sqlite == null)
                throw new ArgumentOutOfRangeException("unitOfWork");
        }

       
        public void Insert_ElectricityRealtime(string meterId, List<RealtimeEnergyReading> realtimeEnergyReadings)
        {

            long meterIdLong = Convert.ToInt32(meterId);

            var meter = sqlite.ElectricityMeter.Where(em => em.id == meterIdLong).FirstOrDefault();
            if (meter != null)
            {
                foreach (var reading in realtimeEnergyReadings)
                {
                    var sqliteReading = new ElectricityRealtime
                    {
                        dateTime = reading.ReadingDateTime,
                        joules = reading.Joules,
                        watts = reading.Watts

                    };
                    meter.ElectricityRealtime.Add(sqliteReading);            
                }
            }

        }





        public List<RealtimeEnergyReading> Get_ElectricityRealtime(string meterId, DateTime dateFrom, DateTime dateTo)
        {
            try
            {
                long meterIdLong = Convert.ToInt32(meterId);
                // using (var sqlite = new CommunergySQLiteEntities(connString))
                {
                    var meter = sqlite.ElectricityMeter.Where(em => em.id == meterIdLong).FirstOrDefault();
                    if (meter != null)
                    {
                        //meter.ElectricityRealtime.Load();
                        var readings = (
                                            from re in sqlite.ElectricityRealtime
                                            where re.dateTime > dateFrom && re.dateTime < dateTo && re.ElectricityMeter.id == meterIdLong

                                            select new RealtimeEnergyReading
                                            {
                                                ReadingDateTime = re.dateTime,
                                                Joules = (int)re.joules.Value,
                                                Watts = (int)re.watts
                                            }
                                        ).ToList();
                        return readings;
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch (Exception e)
            {

                return null;
            }
        }



        public RealtimeEnergyReading GetLastElectricityRealtime(string meterId)
        {
            try
            {
                long meterIdLong = Convert.ToInt32(meterId);
                //using (var sqlite = new CommunergySQLiteEntities(connString))
                {
                    var meter = sqlite.ElectricityMeter.Where(em => em.id == meterIdLong).FirstOrDefault();
                    if (meter != null)
                    {
                        var lastReading = (
                                            from re in sqlite.ElectricityRealtime
                                            where re.dateTime < DateTime.Now && re.ElectricityMeter.id == meterIdLong
                                            orderby re.dateTime descending
                                            select new RealtimeEnergyReading
                                            {
                                                ReadingDateTime = re.dateTime,
                                                Joules = (int)re.joules.Value,
                                                Watts = (int)re.watts
                                            }
                                        ).FirstOrDefault();
                        return lastReading;
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch (Exception e)
            {

                return null;
            }
        }

        public HistoricalEnergyReading GetCumulativeElectricityRealtime(string meterId, DateTime dateFrom, DateTime dateTo)
        {
            long meterIdLong = Convert.ToInt32(meterId);
            
            var timeSpan = dateTo.Subtract(dateFrom);
            var joules = sqlite.ElectricityRealtime.Where(e => e.ElectricityMeter.id == meterIdLong && e.dateTime >= dateFrom && e.dateTime < dateTo).Sum(e => e.joules);

            if (joules == null)
            {
                return null;
            }
            else
            {
                var kwh = ((int)joules.Value).JoulesToKWh();

                var historical = new HistoricalEnergyReading
                {
                    ReadingDateTime = dateFrom,
                    KWh = kwh,
                    TimeSpan = timeSpan
                };
                return historical;
            }
        }

        #endregion
    }
}
